package com.pay.common;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.pay.util.HttpUtil;
import com.pay.util.PropertiesFactoryHelper;
import com.platform.server.response.response.pojo.ReturnData;

import net.sf.json.JSONObject;

public class WxpayDemoUtils {
	
	private static final Logger logger = LoggerFactory.getLogger(WxpayDemoUtils.class);
	
	private static final PropertiesFactoryHelper propFactory = PropertiesFactoryHelper
            .getInstance();

	// 微信支付参数
	public static ReturnData wxPay(String body, String out_trade_no, Integer total_fee, String type, String loca_ip,int temp)throws Exception {
		ReturnData returnData = new ReturnData("");
		/*logger.info("---" + body + "\t out_trade_no=" + out_trade_no + "\t total_fee=" + total_fee + "\t order_id=" + type);*/

		// 随机字符串
		String nonce_str = getRandomString(32);
		// 封装参数
		SortedMap<String, String> signParams = new TreeMap<String, String>();
		signParams.put("appid", WeixinCons.WX_APP_ID); // 微信开放平台审核通过的应用APPID
		signParams.put("mch_id", WeixinCons.WX_MACH_ID); // 微信支付分配的商户号
		signParams.put("nonce_str", nonce_str); // 随机字符串，不长于32位
		signParams.put("body", body); // 商品描述
		signParams.put("attach", type); // 附加数据，在查询API和支付通知中原样返回
		signParams.put("out_trade_no", out_trade_no); // 商户系统内部订单号
		signParams.put("total_fee", String.valueOf(total_fee)); // 订单总金额，单位为分
		signParams.put("spbill_create_ip", loca_ip); // 用户端实际ip
		signParams.put("notify_url", WeixinCons.WX_PAY_NOTIFY_URL);// 接收微信支付异步通知回调地址
		if(temp==2){			
			signParams.put("trade_type", "APP"); // 支付类型
		}else if(temp==21){
			signParams.put("product_id",out_trade_no);
			signParams.put("trade_type", "NATIVE"); // 支付类型
		}else if (temp == 3) {
			signParams.put("trade_type", "JSAPI"); // 支付类型
			signParams.put("openid", type);
		}
		String sign = WeixinPayUtil.createSign("UTF-8", signParams);// 生成签名
		signParams.put("sign", sign); // 签名
		String requestXml = WeixinPayUtil.getRequestXml(signParams);// 生成Xml格式的字符串
		/*logger.info("----------------requestXML-------------------\n" + requestXml);*/
		// 调用统一支付接口
		// requestXml = new String(requestXml.getBytes("utf-8"), "ISO-8859-1");
		String resXml = HttpUtil.postData("https://api.mch.weixin.qq.com/pay/unifiedorder", requestXml);
		// System.out.println("******************微信支付返回*******************\n" +
		// resXml);

		// 返回的result成功结果取出prepay_id：
		Map map = XMLUtil.doXMLParse(resXml);
		String return_code = (String) map.get("return_code");
		// System.out.println(JSONObject.fromObject(map).toString());
		// System.out.println(return_code);
		if (return_code.contains("SUCCESS")) {
			String prepay_id = (String) map.get("prepay_id"); // 获取到prepay_id
			String signs = (String) map.get("sign"); // 获取到prepay_id
			JSONObject jso = new JSONObject();
			String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
			jso.put("appid", WeixinCons.WX_APP_ID); // app_id
			jso.put("partnerid", WeixinCons.WX_MACH_ID); // 微信商户账号
			jso.put("prepayid", prepay_id); // 预付订单id
			jso.put("package", "Sign=WXPay"); // 默认sign=WXPay
			jso.put("noncestr", nonce_str); // 自定义不重复的长度不长于32位
			jso.put("timestamp", timestamp); // 北京时间时间戳
			jso.put("sign", signs);

			SortedMap<String, String> signParam = new TreeMap<String, String>();
			signParam.put("appid", WeixinCons.WX_APP_ID); // app_id
			signParam.put("partnerid", WeixinCons.WX_MACH_ID); // 微信商户账号
			signParam.put("prepayid", prepay_id); // 预付订单id
			signParam.put("package", "Sign=WXPay"); // 默认sign=WXPay
			signParam.put("noncestr", nonce_str); // 自定义不重复的长度不长于32位
			signParam.put("timestamp", timestamp); // 北京时间时间戳
			String signAgain = WeixinPayUtil.createSign("UTF-8", signParam);// 再次生成签名
			jso.put("sign", signAgain);
			// System.out.println("微信支付：+++++++++++++++++++++++++++++++++++++++++");
			// System.out.println(jso.toString());
			if(temp==2||temp == 3){				
				returnData.setData(jso);
			}else if(temp==21){
				returnData.setData("weixin://wxpay/bizpayurl?sr="+jso.toString());
			}
		} else {
			returnData.setMsg((String) map.get("return_msg"));
			returnData.setCode(2);
			returnData.setData(false);
		}
		return returnData;
	}
	
	
	// 表示生成字符串的长度
	private static String getRandomString(int length) {
		length -= 14;
		String base = "abcdefghijklmnopqrstuvwxyz0123456789";
		StringBuffer sb = new StringBuffer();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
		sb.append(sdf.format(new Date()));
		Random random = new Random();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}
	
	/**
	 * 前端调用微信支付返回参数
	 * @param openid
	 * @param body 商品描述
	 * @param out_trade_no 商户订单号
	 * @param total_fee 标价金额
	 * @param type “pay”支付
	 * @param order_id 回传参数
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "unused", "rawtypes" })
	public ReturnData jsApiPay(String openid,String body, String out_trade_no, Integer total_fee,String type,String order_id,HttpServletRequest request) throws Exception{
		ReturnData returnData = new ReturnData();
		logger.info("returnPayParam ---"+body+",,,out_trade_no="+out_trade_no+",total_fee="+total_fee+",,type="+type+",,order_id="+order_id);
		try {
	        String nonce_str = getRandomString(32); //strTime + strRandom;  
	        // 获取发起电脑 ip  
	        String loca_ip=request.getRemoteAddr();//获得本机IP
			
			// 账号信息  
	        String appid = WeixinCons.WX_APP_ID;  // appid  
	        //String appsecret = WeixinCons.app_secret; // appsecret  
	        String mch_id = WeixinCons.WX_MACH_ID; // 商业号  
	        String api_key = WeixinCons.WX_APP_KEY; // key  
	        String notify_url = "";  
	        if (!StringTools.isEmpty(type) && type.equals("pay")) {
	        	notify_url = WeixinCons.WX_PAY_NOTIFY_URL;
			}else {
				if (StringTools.isEmpty(order_id)) {
					throw new Exception("参数异常"); 
				}
				notify_url = WeixinCons.WX_PAY_NOTIFY_URL;
			}
	        logger.info("========================notify_url:"+notify_url);
	        //封装参数
	        SortedMap<String, String> signParams = new TreeMap<String, String>();
		   signParams.put("appid", appid);//app_id
		   signParams.put("body",body);//商品参数信息
		   signParams.put("mch_id", mch_id);//微信商户账号
		   signParams.put("nonce_str", nonce_str);//32位不重复的编号
		   signParams.put("notify_url", notify_url);//回调页面
		   signParams.put("out_trade_no", out_trade_no);//订单编号
		   signParams.put("spbill_create_ip",loca_ip);//请求的实际ip地址
		   signParams.put("total_fee",String.valueOf(total_fee));//支付金额 单位为分
		   signParams.put("trade_type", "JSAPI");//付款类型为扫码
		   signParams.put("openid", openid);
		   if (type == null || !type.equals("pay")) {
	        	signParams.put("attach", order_id); //附加数据，回调时原值返回
			}
		   String sign = WeixinPayUtil.createSign("UTF-8", signParams);//生成签名
		   signParams.put("sign", sign);
		   signParams.remove("key");//调用统一下单无需key（商户应用密钥）
		   String requestXml = WeixinPayUtil.getRequestXml(signParams);//生成Xml格式的字符串
		   logger.info("----------------requestXML:"+requestXml);
			//调用统一支付接口
			String resXml = HttpUtil.postData("https://api.mch.weixin.qq.com/pay/unifiedorder", requestXml);  
			logger.info("////////////////////////\n"+resXml);
			
			//返回的result成功结果取出prepay_id：
			Map result = XMLUtil.doXMLParse(resXml);
			String return_code=(String) result.get("return_code");
			String return_msg=(String) result.get("return_msg");
			if (return_code.contains("SUCCESS")){
				String prepay_id=(String) result.get("prepay_id");//获取到prepay_id
				String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
				
				SortedMap<String, String> signParamsTo = new TreeMap<String, String>();
				signParamsTo.put("appId", appid);//注意一定要大小写
				signParamsTo.put("nonceStr", nonce_str);//
				signParamsTo.put("package", "prepay_id="+prepay_id);//
				signParamsTo.put("signType", "MD5");//
				signParamsTo.put("timeStamp",timestamp);//
			    String paySign = WeixinPayUtil.createSign("UTF-8", signParamsTo);//生成签名
				
				JSONObject jso = new JSONObject();
				jso.put("appid", WeixinCons.WX_APP_ID);
				jso.put("timeStamp",timestamp);
				jso.put("nonceStr",nonce_str);
				jso.put("packageValue","prepay_id="+prepay_id);
				jso.put("signType", "MD5");
			    jso.put("paySign",paySign);
			    
			    returnData.setCode(200);
			    returnData.setData(jso);
			    returnData.setMsg("请求成功");
			}else{
				returnData.setMsg("请求返回有误");
				returnData.setCode(2);
				returnData.setData(false);
				return returnData;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnData;
	}
}
